package otel;

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.instrumentation.runtimemetrics.java17.RuntimeMetrics;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class RuntimeMetricsHooker implements CommandLineRunner {

    private final OpenTelemetry openTelemetry;

    public RuntimeMetricsHooker(OpenTelemetry openTelemetry) {
        this.openTelemetry = openTelemetry;
    }

    @Override
    public void run(String... args) throws Exception {
        RuntimeMetrics runtimeMetrics = RuntimeMetrics.builder(openTelemetry)
                .enableAllFeatures()
                .enableExperimentalJmxTelemetry()
                .build();
        Thread cleanupTelemetry = new Thread(runtimeMetrics::close);
        Runtime.getRuntime().addShutdownHook(cleanupTelemetry);
    }
}
